import logging
from pypinyin import *

import pypinyin
from crontab import CronTab
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from rest_framework.authentication import TokenAuthentication
from rest_framework.parsers import JSONParser
from rest_framework.views import APIView
from backend.common.api_response import JsonResponse
from backend.common.common import record_dynamic
from backend.models import Sys_Environment, Project, Sys_Model, Sys_Project
# from backend.serializers import ProjectSerializer, ProjectDeserializer, \
#     ProjectMemberDeserializer
from backend.serializers import SysEnvironmentSerializer, SysModelSerializer, Sys_ProjectSerializer

logger = logging.getLogger(__name__)  # 这里使用 __name__ 动态搜索定义的 logger 配置，这里有一个层次关系的知识点。
"""
龙盈智达模块
"""


class LyzdProjectList(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def get(self, request):
        """
        获取项目模块
        :param request:
        :return:
        """

        try:
            page_size = int(request.GET.get("page_size", 20))
            page = int(request.GET.get("page", 1))

        except (TypeError, ValueError):
            return JsonResponse(code="999985", msg="page and page_size must be integer!")

        project_name = request.GET.get("project_name")



       # interface_name_zh = request.GET.get("interface_name_zh")
        """获取所有project，去掉status=1的project"""
        project = Sys_Project.objects.filter(status=0)
        """获取所有model，去掉status=1的model"""
        # model = Sys_Model.objects.filter(status=0)

        if project_name:
            obi = Sys_Project.objects.filter(project_name__contains=project_name).order_by("status","-id")

        else:

            obi = Sys_Project.objects.all().order_by("status","-id")

        paginator = Paginator(obi, page_size)  # paginator对象
        total = paginator.num_pages  # 总页数

        try:

            obm = paginator.page(page)

        except PageNotAnInteger:

            obm = paginator.page(1)
        except EmptyPage:

            obm = paginator.page(paginator.num_pages)
        serialize = Sys_ProjectSerializer(obm, many=True)

        return JsonResponse(data={"data": serialize.data,
                                  "page": page,
                                  "total": total
                                  }, code="999999", msg="成功")


#
class AddLyzdProject(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):

        """
        验证参数
        :param data:
        :return:
        """
        try:
            # 必传参数 name, version, type
            if not data["project_name"] or not data["content"]:
                return JsonResponse(code="999996", msg="参数有误！")

        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        新增模块
        :param request:
        :return:
        """
        data = JSONParser().parse(request)
        result = self.parameter_check(data)

        if result:
            return result
        data["create_user"] = request.user.pk
        ptoject_serializer = Sys_ProjectSerializer(data=data)

        try:
            Sys_Project.objects.get(project_name=data["project_name"])

            return JsonResponse(code="999997", msg="存在相同名称")
        except ObjectDoesNotExist:
            with transaction.atomic():

                """
                汉语转英文
                
                """
                project_name_en=lazy_pinyin(data["project_name"])


                project_name_en="".join(project_name_en)

                try:
                    Sys_Project.objects.get(project_name_en=project_name_en)

                    return JsonResponse(code="999997", msg="该项目名称转换拼音过程中发现相同拼音，请修改项目名称")
                except:


                    project_data = Sys_Project(

                        project_name_en=project_name_en,
                        project_name=data["project_name"],  # 用例名称
                        status=0,  # 状态默认0启用
                        content=data['content']

                    )
                    try:
                        project_data.save()

                        return JsonResponse(code="999999", msg="成功")
                    except:
                        return JsonResponse(code="999997", msg="失败")


#
class UpdateLyzdProject(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def parameter_check(self, data):
        """
        校验参数
        :param data:
        :return:
        """
        try:

            if not isinstance(data["id"], int):
                return JsonResponse(code="999996", msg="参数有误！")

            if not data["project_name"] or not data["content"]:
                return JsonResponse(code="999996", msg="参数有误！")

        except KeyError:
            return JsonResponse(code="999996", msg="参数有误！")

    def post(self, request):
        """
        修改项目
        :param request:
        :return:
        """
        data = JSONParser().parse(request)

        result = self.parameter_check(data)
        if result:
            return result
        # 查找项目是否存在
        try:
            obj = Sys_Project.objects.get(id=data["id"])

            if not request.user.is_superuser and obj.user.is_superuser:
                return JsonResponse(code="999983", msg="无操作权限！")
        except ObjectDoesNotExist:
            return JsonResponse(code="999995", msg="项目不存在！")
        # 查找是否相同名称的项目
        project_name = Sys_Project.objects.filter(project_name=data["project_name"]).exclude(id=data["id"])
        if len(project_name):
            return JsonResponse(code="999997", msg="存在相同名称")
        else:

            serializer = Sys_ProjectSerializer(data=data)
            """
            汉语转换拼音
            """
            project_name_en = lazy_pinyin(data["project_name"])

            project_name_en = "".join(project_name_en)



           # Sys_Project.objects.get(project_name_en=project_name_en)






            try:

                Sys_Project.objects.filter(id=data['id']).update(
                    project_name_en=project_name_en,

                    project_name=data['project_name'],
                    content=data['content']
                )
                return JsonResponse(code="999999", msg="编辑成功")
            except:
                return JsonResponse(code="999997", msg="编辑失败")


class EditStatusProject(APIView):
    authentication_classes = (TokenAuthentication,)
    permission_classes = ()

    def post(self, request):

        """查询条件"""
        # 必传参数
        data = JSONParser().parse(request)

        project_id = tuple(data.values())[0]

        status = Sys_Project.objects.filter(id=project_id)

        flag = status[0].status

        try:
            if flag == '0' or flag == 0:

                Sys_Project.objects.filter(id=project_id).update(
                    status=1
                )

                return JsonResponse(code="999999", msg="禁用成功")
            elif flag == '1' or flag == 1:

                Sys_Project.objects.filter(id=project_id).update(
                    status=0
                )

                return JsonResponse(code="999999", msg="启用成功")
        except:
            return JsonResponse(code="999997", msg="内部错误")
